from django.shortcuts import render
import json
from rest_framework.views import APIView
from rest_framework.views import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from users.serializers import UserSerializer
from users.models import User

# 用户注册
class RegisterView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)





class Register(APIView):
    def post(self, request):
        data = request.data
        try:
            User.objects.create(username=data["username"], password=data["password"])
            res_data = {
                "code": 200,
                "msg": "成功",
            }
            return Response(res_data)
        except Exception as e:
            # raise e
            res_data = {
                "code": 500,
                "msg": "失败"
            }
            return Response(res_data)

# 重新用户登录返回函数
def jwt_response_payload_handler(token, user=None, request=None):
    '''
    :param token: jwt生成的token值
    :param user: User对象
    :param request: 请求
    '''
    return {
        'token': token,
        'users': user.username,
        'userid': user.id
    }



# 测试必须携带token才能访问接口
class UserList(APIView):
    # permission_classes = [IsAuthenticated]  # 接口中加权限    #注了不需要token，不注需要token
    # authentication_classes = [JSONWebTokenAuthentication]

    def get(self,request, *args, **kwargs):
        print(request.META.get('HTTP_AUTHORIZATION', None))
        return Response({'name':'zhangsan'})
    def post(self,request, *args, **kwargs):
        return Response({'name':'zhangsan'})
class Show(APIView):
    def get(self,request):
        try:
            id = request.GET.get("id")
            print(id)
            app = User.objects.filter(id=id)
            ser = UserSerializer(app, many=True)
            data = ser.data
            res_data = {
                "code": 200,
                "msg": "查询成功",
                "data": data
            }
            return Response(data=res_data)
        except:
            res_data = {
                "code": 500,
                "msg": "查询失败",
            }
            return Response(data=res_data)